<template>
  <div class="app-container">
    <!-- 返回按钮和标题 -->
    <PageHeader back-text="返回" back-type="back" :title="currentAuditInfo.auditTitle || '工作日志审核详情'" />

    <!-- 审核信息卡片 -->
    <el-card class="mb-6 box-card audit-info-card" v-loading="auditLoading">
      <div class="card-header mb-4">
        <div class="left">
          <span class="title">审核信息</span>
        </div>
        <div class="right">
          <ProjectStatusDisplay label="审核状态" :status-options="approval_commit_status"
            :status-value="currentAuditInfo.auditStatus || '0'" />
        </div>
      </div>

      <el-descriptions :column="3" border>
        <el-descriptions-item label="审核标题">{{ currentAuditInfo.auditTitle || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <dict-tag :options="approval_commit_status" :value="currentAuditInfo.auditStatus || ''" />
        </el-descriptions-item>
        <el-descriptions-item label="项目负责人">{{ currentAuditInfo.proLeaderName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="提交人">{{ currentAuditInfo.submitter || '-' }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">
          {{ parseTime(currentAuditInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentAuditInfo.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 工作日志详情卡片 -->
    <el-card class="mb-6 box-card worklog-detail-card" v-loading="detailLoading">
      <template #header>
        <div class="card-header">
          <span class="title">工作日志明细</span>
        </div>
      </template>

      <div class="worklog-container">
        <div class="scroll-tip-container">
          <div class="scroll-tip">
            <el-icon class="tip-icon">
              <ArrowLeft />
            </el-icon>
            <span class="tip-text">左右滑动查看更多信息</span>
            <el-icon class="tip-icon">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
        <el-table :data="worklogDetailList" border style="width: 100%" :class="{ 'editing-table': isEditing }"
          :row-class-name="tableRowClassName">
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column label="项目名称" width="200" align="center" fixed="left">
            <template #default="scope">
              <span class="project-name">{{ scope.row.proName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="回款节点" width="200" align="center" fixed="left" show-overflow-tooltip>
            <template #default="scope">
              <span class="receive-name">{{ scope.row.receiveName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="技术流程" width="200" fixed="left" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="tech-flow-display">{{ scope.row.techFlow || scope.row.planName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作内容" prop="flowName" fixed="left" width="300" align="left" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.flowName || scope.row.workContent || '暂无工作内容' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作描述" width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.workDescription" type="textarea"
                placeholder="请输入工作描述（必填）" :rows="3" resize="vertical"
                :class="{ 'is-error': !scope.row.workDescription && scope.row.showValidation }"
                @blur="validateWorkDescription(scope.row)" />
              <span v-else>{{ scope.row.workDescription || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作时长(小时)" width="200" align="center">
            <template #default="scope">
              <NumberInput v-if="scope.row.isEditing" v-model="scope.row.workTime" placeholder="工作时长（必填）" :min="0"
                :precision="2" :required="true" :allow-decimal="true" unit="小时"
                :class="{ 'is-error': (!scope.row.workTime || scope.row.workTime <= 0) && scope.row.showValidation }"
                @blur="validateWorkTime(scope.row)" @change="validateWorkTime(scope.row)" />
              <span v-else>{{ scope.row.workTime ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录人" width="150" align="center">
            <template #default="scope">
              <span>{{ scope.row.logRecorderName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" placeholder="请输入备注"
                :rows="3" resize="vertical" />
              <span v-else>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录日期" width="200" align="center">
            <template #default="scope">
              <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.logDate" type="date"
                value-format="YYYY-MM-DD" placeholder="选择日期（必填）" style="width: 160px"
                :disabled-date="(time) => time.getTime() > Date.now()"
                :class="{ 'is-error': !scope.row.logDate && scope.row.showValidation }"
                @blur="validateLogDate(scope.row)" />
              <span v-else>{{ parseTime(scope.row.logDate, '{y}-{m}-{d}') || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审核评分（5分制）" width="200" align="center">
            <template #default="scope">
              <NumberInput v-if="isEditing" v-model="scope.row.auditGrade" placeholder="1-5分" :min="1" :max="5"
                :precision="2" :required="true" :allow-decimal="true" unit="分"
                @change="calculateValidWorkTime(scope.row)" @input="markAsChanged(scope.row)" />
              <span v-else>{{ scope.row.auditGrade ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效工作时长(h)" width="200" align="center">
            <template #default="scope">
              <span class="valid-work-time">{{ scope.row.validWorkTime ?? '-' }}</span>
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无工作日志数据" />
          </template>
        </el-table>

        <!-- 编辑按钮区域 -->
        <div class="edit-actions">
          <div class="left-actions">
            <!-- 左侧可以放置其他操作按钮 -->
          </div>
          <div class="right-actions">
            <el-button v-if="!isEditing" type="primary" size="default" @click="startEdit"
              v-hasPermi="['project:worklog:edit']" :disabled="worklogDetailList.length === 0">
              <el-icon class="mr-1">
                <Edit />
              </el-icon>
              编辑评分
            </el-button>
            <template v-else>
              <el-button type="success" size="default" @click="saveEdit" :loading="saveLoading">
                <el-icon class="mr-1">
                  <Check />
                </el-icon>
                保存
              </el-button>
              <el-button type="info" size="default" @click="cancelEdit">
                <el-icon class="mr-1">
                  <Close />
                </el-icon>
                取消
              </el-button>
            </template>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 审核操作组件 -->
    <AuditAction v-if="checkContractStatus(currentAuditInfo.auditStatus)" :loading="auditActionLoading"
      @audit="handleAuditAction" />

    <!-- 审核流程组件 -->
    <ApprovalFlowDisplay :business-type="'WORK-LOG-AUDIT'" :business-id="String(route.params.auditId)" title="审核流程"
      :auto-load="true" :show-collapse="true" @data-loaded="handleApprovalDataLoaded" @error="handleApprovalError" />
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getWorklogsByAuditId, batchEditProWorklog } from '@/api/project/log/worklog';
import type { ProWorklogAuditVO, ProWorklogVO } from '@/api/project/log/worklog/types';

// 扩展工作日志类型以支持编辑功能
interface WorkLogItem extends ProWorklogVO {
  isEditing?: boolean;
  showValidation?: boolean;
  originalData?: Partial<WorkLogItem> | null;
}
import { NumberInput } from '@/components/NumberInput';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import ApprovalFlowDisplay from '@/components/ApprovalFlowDisplay/index.vue';
import { audit } from '@/api/other/approval/index';
import { checkContractStatus } from '@/utils/permission';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 审核信息
const currentAuditInfo = ref<Partial<ProWorklogAuditVO>>({});
const auditLoading = ref(false);

const { proxy } = getCurrentInstance() as any;
const { approval_commit_status } = toRefs(proxy?.useDict('approval_commit_status'));

// 工作日志详情
const worklogDetailList = ref<WorkLogItem[]>([]);
const detailLoading = ref(false);

// 编辑相关
const isEditing = ref(false);
const saveLoading = ref(false);
const originalWorklogData = ref<WorkLogItem[]>([]);

// 审核操作加载状态
const auditActionLoading = ref(false);

/**
 * 获取审核信息和工作日志详情
 */
const getAuditDetail = async () => {
  const auditId = route.params.auditId as string;
  if (!auditId) {
    ElMessage.error('审核ID不能为空');
    return;
  }

  try {
    detailLoading.value = true;
    // 根据审核ID获取工作日志详情
    const res = await getWorklogsByAuditId(auditId);
    const auditData = res.data || {};

    // 从返回的审核对象中提取工作日志列表
    worklogDetailList.value = auditData.worklogList || [];

    // 从审核对象中提取审核信息
    currentAuditInfo.value = {
      id: auditData.id,
      auditTitle: auditData.auditTitle || '工作日志审核',
      auditStatus: auditData.auditStatus || '1',
      submitter: auditData.submitter || '-',
      createTime: auditData.createTime || '',
      remark: auditData.remark || '',
      proLeaderId: auditData.proLeaderId,
      proLeaderName: auditData.proLeaderName
    };
  } catch (error) {
    console.error('获取工作日志详情失败:', error);
    ElMessage.error('获取工作日志详情失败');
  } finally {
    detailLoading.value = false;
  }
};

// 编辑相关方法
const startEdit = () => {
  // 保存原始数据
  originalWorklogData.value = JSON.parse(JSON.stringify(worklogDetailList.value));
  isEditing.value = true;
};

const saveEdit = async () => {
  // 验证评分数据
  const validationErrors: string[] = [];
  worklogDetailList.value.forEach((item, index) => {
    if (!item.auditGrade || item.auditGrade < 1 || item.auditGrade > 5) {
      validationErrors.push(`第${index + 1}行：审核评分必须在1-5分之间`);
    }
  });

  if (validationErrors.length > 0) {
    proxy?.$modal.msgError(`保存失败：\n${validationErrors.join('\n')}`);
    return;
  }

  saveLoading.value = true;
  try {
    // 构建批量修改数据
    const batchUpdateData = worklogDetailList.value.map((item) => ({
      id: item.id,
      proId: item.proId,
      receiveId: item.receiveId,
      planId: item.planId,
      flowId: item.flowId,
      logDate: item.logDate,
      logRecorder: Number(item.logRecorder),
      workDescription: item.workDescription?.trim(),
      workTime: Number(item.workTime),
      auditGrade: item.auditGrade,
      validWorkTime: item.validWorkTime,
      remark: item.remark?.trim()
    }));

    await proxy?.$modal.confirm('确定要保存评分吗？');
    await batchEditProWorklog(batchUpdateData);
    proxy?.$modal.msgSuccess('评分保存成功');
    isEditing.value = false;
  } catch (error) {
    console.error('保存评分失败:', error);
    proxy?.$modal.msgError('保存评分失败');
  } finally {
    saveLoading.value = false;
  }
};

const cancelEdit = () => {
  // 恢复原始数据
  if (originalWorklogData.value.length > 0) {
    worklogDetailList.value = JSON.parse(JSON.stringify(originalWorklogData.value));
  }
  isEditing.value = false;
  originalWorklogData.value = [];
};


/** 验证工作描述 */
const validateWorkDescription = (item: WorkLogItem) => {
  item.showValidation = true;
  if (!item.workDescription || item.workDescription.trim() === '') {
    return false;
  }
  return true;
};

/** 验证工作时长 */
const validateWorkTime = (item: WorkLogItem) => {
  item.showValidation = true;
  const workTime = Number(item.workTime);
  if (!item.workTime || workTime <= 0 || isNaN(workTime)) {
    return false;
  }
  return true;
};

/** 验证记录日期 */
const validateLogDate = (item: WorkLogItem) => {
  item.showValidation = true;
  if (!item.logDate) {
    return false;
  }
  return true;
};

/** 行样式：编辑中的行高亮显示 */
const tableRowClassName = ({ row }: { row: WorkLogItem }) => (row.isEditing ? 'editing-row' : '');

/** 标记数据已更改 */
const markAsChanged = (row: WorkLogItem) => {
  // 在审核详情页面，我们不需要特殊的更改标记逻辑
  // 这个方法主要是为了保持与index页面的一致性
};

// 计算有效工作时长
const calculateValidWorkTime = (row: WorkLogItem) => {
  if (row.workTime && row.auditGrade) {
    row.validWorkTime = Number(((row.workTime * row.auditGrade) / 5).toFixed(2));
  } else {
    row.validWorkTime = undefined;
  }
};


/**
 * 处理审核操作
 */
const handleAuditAction = async (auditData: { status: string; idea: string }) => {
  try {
    auditActionLoading.value = true;
    await audit({
      businessId: String(route.params.auditId),
      businessType: 'WORK-LOG-AUDIT',
      status: auditData.status,
      idea: auditData.idea
    });

    const message = auditData.status === '1' ? '审核通过成功' : '审核不通过操作完成';
    ElMessage.success(message);
    setTimeout(() => {
      router.push('/project/log/worklog/audit');
    }, 1500);
  } catch (error) {
    console.error('审核操作失败:', error);
    ElMessage.error((error as any)?.message || '审核操作失败');
  } finally {
    auditActionLoading.value = false;
  }
};

/**
 * 处理审核数据加载完成事件
 */
const handleApprovalDataLoaded = (data: any[]) => {
  console.log('审核流程数据加载完成:', data);
};

/**
 * 处理审核错误事件
 */
const handleApprovalError = (error: any) => {
  console.error('审核流程加载失败:', error);
};

onMounted(() => {
  getAuditDetail();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.audit-info-card,
.worklog-detail-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: bold;
  }
}

.worklog-container {
  position: relative;
  margin-top: 20px;

  .scroll-tip-container {
    position: absolute;
    left: 0;
    bottom: 24px;
    flex-shrink: 0;
  }

  .scroll-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 12px;
    color: #909399;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    padding: 6px 12px;
    border-radius: 4px;
    display: inline-flex;
  }

  .tip-icon {
    font-size: 14px;
    color: #909399;
  }

  .tip-text {
    font-size: 12px;
    color: #909399;
  }
}

.edit-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;

  .left-actions {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .right-actions {
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.project-name {
  font-weight: 500;
  color: #409eff;
}

.valid-work-time {
  font-weight: 600;
  color: #f56c6c;
}

/* 编辑状态下的表格样式 */
.editing-table {
  border: 2px solid var(--el-color-primary);
  border-radius: 8px;
}

.editing-table :deep(.el-table__header) {
  background-color: var(--el-color-primary-light-9);
}

/* 项目名称样式 */
.project-name {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

/* 回款节点名称样式 */
.receive-name {
  font-weight: 600;
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

/* 技术流程显示样式 */
.tech-flow-display {
  background-color: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  font-weight: 500;
  color: #1e40af;
  display: block;
  line-height: 1.4;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 编辑状态行背景色 */
:deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 表单验证错误样式 */
:deep(.is-error .el-input__wrapper),
:deep(.is-error .el-textarea__inner),
:deep(.is-error .el-input-number .el-input__wrapper),
:deep(.is-error .number-input-wrapper .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

:deep(.is-error .el-input__wrapper:hover),
:deep(.is-error .el-textarea__inner:hover),
:deep(.is-error .el-input-number .el-input__wrapper:hover),
:deep(.is-error .number-input-wrapper .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

/* 表格内textarea样式优化 */
:deep(.el-table .el-textarea__inner) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

:deep(.el-table .el-textarea__inner:focus) {
  border-color: var(--el-color-primary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
  }

  :deep(.el-button) {
    padding: 8px 16px;
    font-size: 14px;
  }
}
</style>
